<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item label="月份" prop="nowYearMonth">
        <!-- 日期 -->
        <el-date-picker
          v-model="queryParams.nowYearMonth"
          type="month"
          placeholder="请选择月份"
          value-format="YYYY-MM"
        />
      </el-form-item>
      <el-form-item label="日期" prop="dayNum">
        <el-select
          v-model="queryParams.dayNum"
          style="width: 200px"
          placeholder="请选择日期"
        >
          <el-option label="10号" value="10"> </el-option>
          <el-option label="25号" value="25"> </el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          @click="handleExport"
          v-hasPermi="['system:contract:transactionType:add']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row> -->

    <el-table
      v-loading="loading"
      :data="dataList"
      :span-method="spanMethod"
      border
      @selection-change="handleSelectionChange"
    >
      <el-table-column label="区域" align="center" prop="regionName" />
      <el-table-column
        label="店面"
        align="center"
        prop="storeName"
        width="150"
      />
      <el-table-column label="买卖收入" align="center" prop="incomeFromTrading" />
      <el-table-column label="服务费店面收入" align="center" prop="serviceFeesStoreIncome" />
      <el-table-column
        label="租赁收入"
        align="center"
        prop="leaseFeesIncome"
      />
      <el-table-column
        label="服务费公司收入"
        align="center"
        prop="serviceFeesCompanyIncome"
      />
      <el-table-column
        label="办件费"
        align="center"
        prop="processingFee"
      />
      <el-table-column label="保险收入/金额" align="center" prop="insurance" />
      <el-table-column label="手续费" align="center" prop="handlingEe" />
      <el-table-column label="店面系统费" align="center" prop="handlingFee" />
      <el-table-column label="往月未扣费用" align="center" prop="monthNoAmount" />
      <el-table-column label="其他金额" align="center" prop="other" />
      <el-table-column label="返佣金额" align="center" prop="commissionAmount" />
       <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:notice:edit']">修改</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    /> -->

    <!-- 添加或修改岗位对话框 -->
    <el-dialog :title="title" v-model="open" width="700px" append-to-body>
      <el-form ref="noticeRef" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label-width="120px" label="服务费公司收入" prop="serviceFeesCompanyIncome">
              <el-input
                  v-model="form.serviceFeesCompanyIncome"
                  placeholder="请输入服务费公司收入"
                 type="number"
              >
                <template #append>元</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label-width="120px" label="办件费" prop="processingFee">
              <el-input
                  v-model="form.processingFee"
                  placeholder="请输入办件费"
                  type="number"
              >
                <template #append>元</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label-width="120px" label="保险收入/金额" prop="insurance">
              <el-input
                  v-model="form.insurance"
                  placeholder="请输入保险收入/金额"
                  type="number"
              >
                <template #append>元</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label-width="120px" label="手续费" prop="handlingFee">
              <el-input
                  v-model="form.handlingFee"
                  placeholder="请输入手续费"
                  type="number"
              >
                <template #append>元</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label-width="120px" label="店面系统费" prop="storeSystemFee">
              <el-input
                  v-model="form.storeSystemFee"
                  placeholder="请输入店面系统费"
                  type="number"
              >
                <template #append>元</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label-width="120px" label="往月未扣费用" prop="monthNoAmount">
              <el-input
                  v-model="form.monthNoAmount"
                  placeholder="请输入往月未扣费用"
                  type="number"
              >
                <template #append>元</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="getRebateOrder">
import {
  addRefund,
  queryRefund,
  saveHzRebate,
  rebateQuery,
  deleteRefund,
  submitAudit,

} from "@/api/business/rebate";
import {
  listFinishReg,
  submitCompletedReview,
} from "@/api/dailyNewspaper/finishReg";
// import { monthPaper } from "@/api/dailyNewspaper/addDetails";
import { getRebateOrder } from "@/api/mouthNewspaper/endStatistics";
import { onMounted } from "vue";
const { proxy } = getCurrentInstance();
const { sys_normal_disable } = proxy.useDict("sys_normal_disable");
import { reactive } from "vue";
import {addNotice, updateNotice} from "@/api/configure/notice.js";
const dataList = ref([]);
const open = ref(false);
const openDetail = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const data = reactive({
  form: {},
  queryParams: {
    nowYearMonth: "",
    dayNum: "10",
  },
  rules: {
    serviceFeesCompanyIncome: [{ required: true, message: "服务费公司收入不能为空", trigger: "blur" }],
    processingFee: [{ required: true, message: "办件费收入不能为空", trigger: "blur" }],
    insurance: [{ required: true, message: "保险收入/金额收入不能为空", trigger: "blur" }],
    handlingEe: [{ required: true, message: "手续费收入不能为空", trigger: "blur" }],
    storeSystemFee: [{ required: true, message: "店面系统费收入不能为空", trigger: "blur" }],
    monthNoAmount: [{ required: true, message: "往月未扣费用收入不能为空", trigger: "blur" }]
  },
});

const { queryParams,form, rules } = toRefs(data);


onMounted(() => {
  const curMonth = new Date().getMonth() + 1;
  const nowYearMonth =
    new Date().getFullYear() +
    "-" +
    (curMonth < 10 ? "0" + curMonth : curMonth);
  queryParams.value.nowYearMonth = nowYearMonth;
  queryParams.value.dayNum = "10";
  getList();
});
/** 查询岗位列表 */
function getList() {
  console.log('触发加载方式')
  loading.value = true;
  getRebateOrder(queryParams.value).then((response) => {
    const sortedData = sortDataForMerge(response.data, [
      "regionName",
      "storeName",
      "franchiseeName",
    ]);

    dataList.value = sortedData;

    total.value = response.total;
    loading.value = false;
  });
}
const mergeMap = computed(() => {
  return getHierarchicalMergeMap(dataList.value);
});
// 排序
function sortDataForMerge(data, fields) {
  return [...data].sort((a, b) => {
    for (const field of fields) {
      if (a[field] !== b[field]) {
        return a[field] > b[field] ? 1 : -1;
      }
    }
    return 0;
  });
}
// 合并行
function spanMethod({ row, column, rowIndex }) {
  const prop = column.property;
  const map = mergeMap.value;

  if (map[prop] && map[prop][rowIndex] != null) {
    return [map[prop][rowIndex], 1];
  }

  for (const startRow in map[prop] || {}) {
    const span = map[prop][startRow];
    if (rowIndex > +startRow && rowIndex < +startRow + span) {
      return [0, 0];
    }
  }
}

//合并行，得出需要合并的数据
function getHierarchicalMergeMap(
  data,
  fields = ["regionName", "storeName", "franchiseeName"]
) {
  const mergeMap = {};
  const rowCount = data.length;

  fields.forEach((field, level) => {
    mergeMap[field] = {};

    let startRow = 0;
    let spanCount = 1;

    for (let i = 1; i <= rowCount; i++) {
      const prev = data[i - 1];
      const curr = data[i];

      // 判断当前行是否和上一行在所有上级字段上相同
      const isSameGroup = fields
        .slice(0, level + 1)
        .every((f) => curr?.[f] === prev?.[f]);

      if (isSameGroup) {
        spanCount++;
      } else {
        if (spanCount > 1) {
          mergeMap[field][startRow] = spanCount;
        }
        startRow = i;
        spanCount = 1;
      }
    }
  });

  return mergeMap;
}

/**修改按钮操作 */
function handleUpdate(row) {
  reset()
  const noticeId = row.id
  rebateQuery(noticeId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改"
  })
}
/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}
function handleDetail(row) {
  queryRefund(row.id).then((response) => {
    form.value = response.data;
    openDetail.value = true;
  });
}
/** 表单重置 */
function reset() {
  form.value = {};
  proxy.resetForm("postRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.postId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

const refundAddRef = ref();
/** 提交按钮 */
function submitForm() {
  proxy.$refs["noticeRef"].validate(valid => {
    if (valid) {
      saveHzRebate(form.value).then(response => {
        proxy.$modal.msgSuccess("修改成功")
        open.value = false
        getList()
      })
    }
  })

}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "/system/saleDetails/export",
    {
      ...queryParams.value,
    },
    `addDetails_${new Date().getTime()}.xlsx`
  );
}
</script>
<style scoped></style>
